package com.heima.comment.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author WSJ
 * @Date 2022-03-12-14:26
 * @Version 1.0 （版本号）
 */
@Component
public class AppInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户id
        String userId = request.getHeader("userId");
        //保存到线程中
        if (!StringUtils.isEmpty(userId)&&!"0".equals(userId)) {
            AppThreadLocalUtil.set(new User(Integer.parseInt(userId)));
        }
        return true;
    }

    /**
     * 后置拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AppThreadLocalUtil.remove();
    }
}
